package com.adingxiong.pm.controller;


import com.adingxiong.pm.entity.MailBean;
import com.adingxiong.pm.entity.Pmuser;
import com.adingxiong.pm.model.Result;
import com.adingxiong.pm.model.RetCode;
import com.adingxiong.pm.server.IPmuserService;
import com.adingxiong.pm.util.MD5Utils;
/*import com.adingxiong.pm.util.MailUtils;*/
import com.adingxiong.pm.util.TokenUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;


/**
 * @author a
 */
@RestController
@RequestMapping("/user")
@Api(tags = "登录注册")
@CrossOrigin
public class LoginController {
    private Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Autowired
    private IPmuserService iPmuserService;

    /*@Autowired
    private MailUtils mailUtils;*/

    @ApiOperation(value = "用户登录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "用户名", required = true, paramType = "query", example = "admin"),
            @ApiImplicitParam(name = "password", value = "密码", required = true, paramType = "query", example = "123456")
    })
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public Result login(HttpServletResponse response, HttpServletRequest request,
                        String name, String password
    ) {
        if(StringUtils.isEmpty(name) || StringUtils.isEmpty(password)){
            return new Result().setCode(RetCode.PARAM_ERROR.code).setMsg(RetCode.PARAM_ERROR.msg);
        }
        String mdpwd = MD5Utils.string2MD5(password);
        QueryWrapper<Pmuser> query = new QueryWrapper<>();
        Map<String, Object> param = new HashMap<>();
        param.put("name", name);
        param.put("password", mdpwd);
        query.allEq(param);
        Pmuser user = iPmuserService.getOne(query);
        if (user == null) {
            return new Result().setCode(RetCode.PARAM_VALUE_ERROR).setMsg("用户名或者密码错误");
        }
        String token = TokenUtils.getToken(user.getId(), name);
        response.addHeader("tokenHeader", token);
        Map<String,Object> result = new HashMap<>();
        result.put("name",name);
        result.put("userId",user.getId());
        result.put("token",token);
        return new Result<>().setCode(RetCode.SUCCESS).setMsg("登录成功").setData(result);

    }

    /*@ApiOperation(value = "邮箱发送")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sendName", value = "收件人姓名", required = true, paramType = "query", example = "1374543195@qq.com"),
            @ApiImplicitParam(name = "sendEm", value = "收件人邮箱", required = true, paramType = "query", example = "熊超")
    })
    @RequestMapping(value = "/sendEmail", method = RequestMethod.GET)
    public Result sendEmail(String sendName, String sendEm) {
        if (StringUtils.isEmpty(sendEm) || StringUtils.isEmpty(sendEm)) {
            return new Result().setCode(RetCode.FAIL).setMsg("参数为空");
        }
        MailBean mailBean = new MailBean();
        mailBean.setRecipient(sendEm);
        String msgcode = String.valueOf(new Random().nextInt(899999) + 100000);
        String content = "<h2>尊敬的" + sendName + "：</h2>" +
                "<p style='padding-left:50px;'>【注册验证码】: 尊敬的用户，您后台管理系统注册的验证码为:<span style='font-size:16px;font-weight:bold'>" + msgcode + "</span>" +
                " （有效期为五分钟）</p>";
        mailBean.setContent(content);
        mailBean.setSubject("系统注册");
        try {
            mailUtils.sendHTMLMail(mailBean);
            return new Result().setCode(RetCode.SUCCESS).setMsg("邮箱发送成功");
        } catch (Exception e) {
            logger.error("邮箱注册异常：" + e);
            return new Result().setCode(RetCode.FAIL).setMsg("邮箱注册异常");
        }


    }
*/
    @ApiOperation(value = "密码解密")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "password", value = "加密密码", dataType = "String" ,paramType = "query" , required = true)
    })
    @RequestMapping(value = "/despwd", method = RequestMethod.GET)
    public Result getPassWord(String password) {
        String pwd = MD5Utils.convertMD5(MD5Utils.convertMD5(password));
        return new Result<>().setCode(RetCode.SUCCESS).setMsg("解密成功").setData(pwd);
    }

    public static void main(String args[]) {

        String verifyCode = String.valueOf(new Random().nextInt(899999) + 100000);
        System.out.println(verifyCode);
    }

}
